package com;

public class UsersManager extends Database{

	public boolean queryUser(String username, String password, String sessionID){
		try{
			connectToDatabase();
			preparedStatement = connect.prepareStatement("SELECT * FROM `citiquantsdb`.`users` WHERE `Username` = ? AND `Password` = ?;");
			preparedStatement.setString(1, username);
			preparedStatement.setString(2, password);
			resultSet = preparedStatement.executeQuery();
			if (resultSet.next()){
				preparedStatement = connect.prepareStatement("REPLACE INTO `citiquantsdb`.`users` (`Username`, `Password`, `Session ID`, `isAdmin`) VALUES "
						+ "(?, ?, ?, ?);");
				preparedStatement.setString(1, username);
				preparedStatement.setString(2, password);
				preparedStatement.setString(3, sessionID);
				preparedStatement.setString(4, resultSet.getString("isAdmin"));
				preparedStatement.execute();

				return true;
			}
			return false;
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close();
		}
		return false;
	}
	
	public void resetSession(String sessionID){
		try{
			connectToDatabase();
			preparedStatement = connect.prepareStatement("SELECT * FROM `citiquantsdb`.`users` WHERE `Session ID` = ?;");
			preparedStatement.setString(1, sessionID);
			resultSet = preparedStatement.executeQuery();

			if (resultSet.next()){
				preparedStatement = connect.prepareStatement("REPLACE INTO `citiquantsdb`.`users` (`Username`, `Password`, `Session ID`, `isAdmin`) VALUES "
						+ "(?, ?, ?, ?);");
				preparedStatement.setString(1, resultSet.getString("Username"));
				preparedStatement.setString(2, resultSet.getString("Password"));
				preparedStatement.setString(3, "");
				preparedStatement.setString(4, resultSet.getString("isAdmin"));
				preparedStatement.execute();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close();
		}
	}
	
	// Returns 0 if the user is not logged in
	// Returns 1 if the user is logged in and is a regular user
	// Returns 2 if the user is logged in and is an admin
	public int querySession(String sessionID){
		try{
			connectToDatabase();
			preparedStatement = connect.prepareStatement("SELECT * FROM `citiquantsdb`.`users` WHERE `Session ID` = ?;");
			preparedStatement.setString(1, sessionID);
			resultSet = preparedStatement.executeQuery();

			if (resultSet.next()){
				String isAdmin = resultSet.getString("isAdmin");
				if (isAdmin != null && isAdmin.equals("true")){
					return 2;
				}
				return 1;
			}
			return 0;
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close();
		}
		return 0;	
	}
	
}
